import {observable, action} from 'mobx-miniprogram'
import {hashCode} from "@src/common/utils";
import $math from "@src/common/math";

export default observable({
  // 数据字段
  totalFee: 0,
  num: 0,
  cartList: [],
  shopId: null,
  maxAdd: 10,

  // actions
  initCart: action(function (shopId) {
    if (shopId === this.shopId) {
      return;
    }
    // 从缓存中加载购物车 todo 分店铺购物车
    this.shopId = shopId;
    let cacheShopId = wx.getStorageSync("catering:shopId");
    if (cacheShopId === shopId) {
      let cartList = wx.getStorageSync("catering:cartList");
      this.cartList = cartList ? cartList : []
    } else {
      this.cartList = []
      wx.setStorageSync("catering:shopId", shopId);
      wx.removeStorageSync("catering:cartList");
    }
    this.calcFee();
  }),

  addCart: action(function (goods) {
    let cartList = this.cartList.concat([]);
    let index = null;
    for (let i = 0; i < cartList.length; i++) {
      let item = cartList[i]
      if (item.id === goods.id && item.spec === goods.spec &&
          hashCode(JSON.stringify(item.attrList)) === hashCode(JSON.stringify(goods.attrList))) {
        index = i;
        break;
      }
    }
    if (index !== null) {
      cartList[index].count = cartList[index].count + 1
    } else {
      let remark = [];
      if (goods.spec) {
        remark.push(goods.spec)
      }
      if (goods.attrList) {
        remark.push(...goods.attrList)
      }
      cartList.push({...goods, count: 1, remark: remark.join(",")})
    }
    this.cartList = cartList;
    this.calcFee()
    wx.setStorageSync("catering:cartList", cartList);
  }),

  reduceCart: action(function (goods) {
    let cartList = this.cartList.concat([]), index = null;
    for (let i = 0; i < this.cartList.length; i++) {
      let item = cartList[i]
      if (item.id === goods.id
          && item.spec === goods.spec
          && JSON.stringify(item.attrList) === JSON.stringify(goods.attrList)) {
        index = i;
        break;
      }
    }
    if (index === null) {
      console.warn("no reduce", goods)
      return;
    }
    if (cartList[index].count <= 1) {
      cartList.splice(index, 1);
    } else {
      cartList[index].count = cartList[index].count - 1;
    }
    this.cartList = cartList;
    this.calcFee()
    wx.setStorageSync("catering:cartList", this.cartList);
  }),

  calcFee: action(function () {
    // 点餐的金额单位时元, 注意坑
    if (this.cartList.length === 0) {
      this.totalFee = 0;
      this.num = 0;
      return;
    }
    let totalFee = 0;
    let num = 0;
    for (let goods of this.cartList) {
      num = num + goods.count;
      totalFee = $math.add(totalFee, $math.mul(goods.price, goods.count, 2));
    }
    this.num = num;
    this.totalFee = totalFee;
  }),
  clearCart: action(function () {
    this.cartList = [];
    this.calcFee();
    wx.removeStorageSync("catering:cartList");
  })
})

